const { spawn } = require('child_process');
const path = require('path');

// 简易颜色函数
const colors = {
    yellow: str => `\x1b[33m${str}\x1b[0m`,
    green: str => `\x1b[32m${str}\x1b[0m`,
    red: str => `\x1b[31m${str}\x1b[0m`,
    blue: str => `\x1b[34m${str}\x1b[0m`,
    gray: str => `\x1b[90m${str}\x1b[0m`,
    cyan: str => `\x1b[36m${str}\x1b[0m`,
    bold: str => `\x1b[1m${str}\x1b[0m`,
};

async function runCommand(command, cwd, name) {
    console.log(colors.yellow(`\n🚀 开始构建 ${name} 项目...`));
    console.log(colors.gray(`> 工作目录: ${cwd}`));
    console.log(colors.gray(`> 执行命令: ${command}\n`));

    const [cmd, ...args] = command.split(' ');
    const child = spawn(cmd, args, {
        cwd,
        shell: true,
        stdio: 'pipe'
    });

    child.stdout.on('data', (data) => {
        process.stdout.write(colors.blue(`[${name}] `) + data);
    });

    child.stderr.on('data', (data) => {
        process.stderr.write(colors.red(`[${name} ERROR] `) + data);
    });

    return new Promise((resolve) => {
        child.on('close', (code) => {
            console.log('\n');
            if (code === 0) {
                console.log(colors.green(`✅ ${name} 构建成功！`));
                resolve(true);
            } else {
                console.log(colors.red(`❌ ${name} 构建失败，退出码: ${code}`));
                resolve(false);
            }
        });

        child.on('error', (error) => {
            console.error(colors.red(`❌ ${name} 启动失败: ${error.message}`));
            resolve(false);
        });
    });
}

async function runCopyScript() {
    const baseDir = process.cwd();
    const copyScriptPath = path.join(baseDir, 'copy-script.js');

    console.log(colors.yellow('\n📦 开始执行复制脚本...'));

    return new Promise((resolve) => {
        const child = spawn('node', [copyScriptPath], {
            stdio: 'inherit'
        });

        child.on('close', (code) => {
            if (code === 0) {
                console.log(colors.green('\n✅ 复制脚本执行成功！'));
                resolve(true);
            } else {
                console.log(colors.red(`\n❌ 复制脚本执行失败，退出码: ${code}`));
                resolve(false);
            }
        });

        child.on('error', (error) => {
            console.error(colors.red(`❌ 复制脚本启动失败: ${error.message}`));
            resolve(false);
        });
    });
}

async function main() {
    console.log(colors.cyan('\n🏗️ 开始完整构建流程 🏗️'));
    console.log(colors.cyan('='.repeat(60)));

    const baseDir = process.cwd();

    try {
        // 1. 构建Vue项目
        const vueDir = path.join(baseDir, '../Vue');
        const vueSuccess = await runCommand('npm run build', vueDir, 'Vue');

        if (!vueSuccess) {
            console.log(colors.red('\n🚫 Vue构建失败，终止流程'));
            process.exit(1);
        }

        // 2. 构建Angular项目
        const angularDir = path.join(baseDir, '../Angular');
        const angularSuccess = await runCommand('npm run build', angularDir, 'Angular');

        if (!angularSuccess) {
            console.log(colors.red('\n🚫 Angular构建失败，终止流程'));
            process.exit(1);
        }

        // 3. 运行复制脚本
        const copySuccess = await runCopyScript();

        if (!copySuccess) {
            console.log(colors.red('\n🚫 复制操作失败'));
            process.exit(1);
        }

        // 构建成功
        console.log(colors.green('\n🎉 所有构建步骤已完成！'));
        console.log(colors.green('='.repeat(60)));
        console.log(colors.green(`最终输出目录: ${path.join(baseDir, '../Node/dist')}`));
        console.log('\n');
    } catch (error) {
        console.error(colors.red('\n⚠️ 构建过程中发生未预期错误:'));
        console.error(error);
        process.exit(1);
    }
}

main();